<?php


namespace catchAdmin\archives\excel;


use app\common\lib\Redis;
use app\common\lib\ZhyxMongo;
use app\common\model\PatientInfo;
use app\common\model\PatientInfo as PatientInfoModel;
use catcher\exceptions\FailedException;
use catcher\library\excel\ExcelContract;
use MongoDB\BSON\ObjectId;
use MongoDB\BSON\UTCDateTime;
use PhpOffice\PhpSpreadsheet\Style\Alignment;

class PatientExport implements ExcelContract
{
    /**
     * 设置头部
     *
     * @time 2020年09月08日
     * @return string[]
     */
    public function headers(): array
    {

        // TODO: Implement headers() method.
        return [
            "患者ID", "单次就诊唯一标识号", "就诊类型", "就诊卡号", "门诊号", "病案号", "住院号", "姓名", "性别", "年龄（岁）", "出生日期", "随访流水号", "随访方式", "初治年龄", "初治日期", "随访周期", "随访日期", "随访状态代码", "随访状态", "身体状况", "死亡日期", "死亡原因", "复发日期", "复发诊断编码", "复发诊断名称", "首次复发转移日期", "转移日期", "转移部位", "转移诊断编码", "转移诊断名称", "多原发诊断编码", "多原发诊断名称", "随访结论", "证件类型", "身份证号", "现住址", "联系电话", "联系电话2", "邮箱", "微信", "紧急联系人1", "紧急联系人电话1", "紧急联系人2", "紧急联系人电话2", "扩展字段1", "扩展字段2", "记录状态", "不良反应"

        ];
    }

    /**
     * 处理数据
     *
     * @time 2020年09月08日
     * @return array
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\db\exception\DataNotFoundException
     */
    public function sheets(): array
    {
        set_time_limit(0);
        $param = request()->param();

        $patientIdArr = [];
        $condition=[];
        if (isset($param["request_id"]) && !empty($param["request_id"])) {

            //$patientIdArr = Redis::getInstance()->redis->smembers("patient_data:" . trim($param["request_id"]));
            $condition = Redis::getInstance()->redis->get("patient_data:" . trim($param["request_id"]));

            if (empty($condition)) {
                throw new FailedException("没有数据，无需导出");
            }

        }
        $match = json_decode($condition,true);
       $group = ['_id' => '$_id', 'patientUUID' => ['$first' => '$_id'], 'mode' => ['$last' => '$info.mode'], 'name' => ['$first' => '$name'], 'followup_sn' => ['$last' => ['$toString' => '$info._id']], 'first_treat_age' => ['$first' => '$first_treat_age'], 'first_treat_datetime' => ['$first' => '$first_treat_datetime'], 'medicalRecordsNo' => ['$last' => '$medicalRecordsNo'], 'inhospitalNo' => ['$last' => '$inList.inhospitalNo'], 'diseaseNo' => ['$last' => '$inList.diseaseNo'], 'diagnose' => ['$last' => '$inList.diagnose'], 'clinicNo' => ['$last' => '$outList.clinicNo'], 'diseaseCode' => ['$last' => '$outList.diseaseList.disease.diseaseCode'], 'diseaseName' => ['$last' => '$outList.diseaseList.disease.diseaseName'], 'patient_id' => ['$first' => '$patient_id'], 'inpatientNo' => ['$first' => '$inpatientNo'], 'visit_card_no' => ['$last' => '$visitcardno'], 'sex' => ['$first' => '$sex'], 'birthdate' => ['$first' => '$birthdate'], 'death' => ['$last' => '$death'], 'bz' => ['$first' => '$bz'], 'idno' => ['$first' => '$idno'], 'calc_date_node' => ['$first' => '$calc_date_node'], 'accountAddress' => ['$first' => '$accountAddress'], 'presentTelphone' => ['$first' => '$presentTelphone'], 'contactName' => ['$first' => '$contactName'], 'contactTelphone' => ['$first' => '$contactTelphone'], 'liveStatus' => ['$first' => '$liveStatus'], 'followup_datetime' => ['$last' => '$info.pushtime'], 'followup_status_code' => ['$last' => '$info.result'], 'followup_status' => ['$last' => '$info.resultName'], 'type' => ['$last' => '$is_in_hospital'], 'recur_datetime' => ['$last' => '$info.recurrence.checkTime'], 'mets_datetime' => ['$last' => '$info.transfer.checkTime'], 'mets_site' => ['$last' => '$info.transfer.place'], 'health_status' => ['$last' => '$info.health_status'], 'followup_conclusion' => ['$last' => '$info.followup_conclusion'], 'adverse_reaction' => ['$last' => '$info.adverse_reaction']];
        if (isset($param["is_mz"]) && !empty($param["is_mz"])) {
            $group["type"] = ['$first' => 0];
        }

        $pipLine = [['$match' => $match], ['$lookup' => ['from' => 'follow_history', 'localField' => 'patientId', 'foreignField' => 'patientId', 'as' => 'info']], ['$unwind' => ['path' => '$info', 'preserveNullAndEmptyArrays' => true]], ['$group' => $group], ['$addFields' => ['mz_count' => ['$cond' => ['if' => ['$ifNull' => ['$calc_date_node.visit_time_arr', false]], 'then' => ['$size' => '$calc_date_node.visit_time_arr'], 'else' => 0]], 'zy_count' => ['$cond' => ['if' => ['$ifNull' => ['$calc_date_node.inhospitalDateArr', false]], 'then' => ['$size' => '$calc_date_node.inhospitalDateArr'], 'else' => 0]], 'visit_type' => ['$switch' => ['branches' => [['case' => ['$eq' => ['$type', 1]], 'then' => '住院'], ['case' => ['$eq' => ['$type', 2]], 'then' => '出院']], 'default' => '门诊']]]], ['$addFields' => ['calc_count' => ['$cond' => ['if' => ['$eq' => ['$info.type', 1]], 'then' => '$mz_count', 'else' => '$zy_count']]]], ['$addFields' => ['no' => ['$cond' => ['if' => ['$eq' => ['$type', 0]], 'then' => '$clinicNo', 'else' => '$inhospitalNo']]]], ['$addFields' => ['diseaseCode' => ['$cond' => ['if' => ['$eq' => ['$type', 0]], 'then' => ['$arrayElemAt' => ['$diseaseCode', 0]], 'else' => '$diseaseNo']], 'diseaseValue' => ['$cond' => ['if' => ['$eq' => ['$type', 0]], 'then' => ['$arrayElemAt' => ['$diseaseName', 0]], 'else' => '$diagnose']]]], ['$sort' => ['patientUUID' => -1]], ['$project' => ['_id' => false, 'patient_id' => ['$ifNull' => ['$patient_id', '']], 'visit_sn' => ['$concat' => ['$patient_id', '|', ['$toString' => '$no'], '|', ['$toString' => '$calc_count'], '|', '$visit_type']], 'visit_type' => ['$ifNull' => ['$visit_type', '']], 'visit_card_no' => ['$ifNull' => ['$visit_card_no', '']], 'outpatient_no' => ['$ifNull' => ['$clinicNo', '']], 'medical_record_no' => ['$ifNull' => ['$medicalRecordsNo', '']], 'inpatient_no' => ['$ifNull' => ['$inhospitalNo', '']], 'name' => '$name', 'gender' => ['$ifNull' => ['$sex', '']],  'age' => ['$cond' => ['if' => ['$ifNull' => ['$birthdate', false]], 'then' => ['$subtract' => [['$year' => new UTCDateTime()], ['$toInt' => ['$substr' => ['$birthdate', 0, 4]]]]], 'else' => '']], 'date_of_birth' => '$birthdate', 'followup_sn' => ['$ifNull' => ['$followup_sn', '']], 'followup_method' => ['$cond' => ['if' => ['$eq' => ['$mode', 1]], 'then' => '微信', 'else' => ['$cond' => ['if' => ['$eq' => ['$mode', 2]], 'then' => '短信', 'else' => ['$cond' => ['if' => ['$eq' => ['$mode', 4]], 'then' => '电话', 'else' => ['$ifNull' => ['$mode', '无']]]]]]]], 'first_treat_age' => ['$ifNull' => ['$first_treat_age', '']], 'first_treat_datetime' => ['$ifNull' => ['$first_treat_datetime', '']], 'followup_period' => ['$ceil' => ['$divide' => [['$subtract' => [new UTCDateTime(), ['$toDate' => '$followup_datetime']]], 86400000]]], 'followup_datetime' => ['$ifNull' => ['$followup_datetime', '']], 'followup_status_code' => ['$ifNull' => ['$followup_status_code', '']], 'followup_status' => ['$ifNull' => ['$followup_status', '']], 'health_status' => ['$ifNull' => ['$health_status', '']], 'death_datetime' => ['$ifNull' => ['$death.deathDate', '']], 'cause_of_death' => ['$ifNull' => ['$death.causeOfDeath', '']], 'recur_datetime' => ['$ifNull' => ['$recur_datetime', '']], 'recur_diag_code' => '', 'recur_diag_name' => '', 'first_recur_mets_date' => '', 'mets_datetime' => ['$ifNull' => ['$mets_datetime', '']], 'mets_site' => ['$ifNull' => ['$mets_site', '']], 'mets_diag_code' => '', 'mets_diag_name' => '', 'mulpri_diag_code' => ['$ifNull' => ['$diseaseCode', '']], 'mulpri_diag_name' => ['$ifNull' => ['$diseaseValue', '']], 'followup_conclusion' => ['$ifNull' => ['$followup_conclusion', '']], 'certificate_type' => '居民身份证', 'certificate_no' => ['$ifNull' => [['$concat' => ['$idno', ' ']], '']], 'current_address' => ['$ifNull' => ['$accountAddress', '']], 'phone_no' => ['$ifNull' => ['$presentTelphone', '']], 'phone_no2' => '', 'email' => '', 'weixin' => '', 'contact_person1' => ['$ifNull' => ['$contactName', '']], 'contact_phone_no1' => ['$ifNull' => ['$contactTelphone', '']], 'contact_person2' => '', 'contact_phone_no2' => '', 'extend_data1' => '', 'extend_data2' => '', 'record_status' => '1', 'adverse_reaction' => ['$ifNull' => ['$adverse_reaction', '']]]]];

        $result = ZhyxMongo::getInstance()->setCollection('patient_info')->aggregate($pipLine, ["allowDiskUse" => true]);

        $rst = [];
        $mode = config('dictionary.follow_mode');
        foreach ($result as $k => $v) {
            $v["certificate_no"] = $v["certificate_no"] . " ";
            $date1 = new \DateTime(date("Y-m-d"));
            $date2 = new \DateTime($v['followup_datetime']);
            $interval = $date1->diff($date2);
            $day = $interval->days;
            if ($day == 0) {
                $day = 1;
            }
            $v["followup_period"] = $day;
            if (in_array($v['followup_method'], [1, 2, 4])) {
                $v['followup_method'] = $mode[$v['followup_method']];
            }
            $rst[] = (array)$v;
        }
        return $rst;
    }

    public function setRow(): int
    {
        return 1;
    }
}